<template>
  <div class="navbar">
    <div class="left-side" :title="$t('navbar.logo.to')" @click="toDashboard">
      <a-space>
        <img alt="logo" :src="logoTop" />
        <a-typography-title
          :style="{ margin: 0, fontSize: '16px', fontWeight: 'bold' }"
          :heading="5"
        >
          {{ $t('navbar.logo.title') }}
        </a-typography-title>
      </a-space>
    </div>
    <a-divider
      v-if="projectModeControl"
      direction="vertical"
      :margin="24"
      :style="{ fontSize: '32px' }"
    />
    <div class="center-side">
      <template v-if="projectModeControl">
        <div class="mode-box">
          <div class="mode-logo">{{ miniMode }}</div>
          <a-select v-model="globalMode" class="mode-select">
            <a-option
              v-for="item of modeList"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </a-select>
        </div>
        <a-dropdown
          class="prj-dropdown"
          :popup-max-height="false"
          @select="projectChange"
        >
          <a-button class="project-select"
            >{{ currenPrjName }} <icon-down :size="16"
          /></a-button>
          <template #content>
            <a-dgroup>
              <template #title>
                <div class="g-title"
                  ><img src="@/assets/images/xm.png" /><span>项目</span></div
                >
              </template>
              <a-doption
                v-for="project in projectList.filter((e) => {
                  return e.isTemplate === 0;
                })"
                :key="project.id"
                :value="project.id"
                ><span class="prj-dot"></span>{{ project.name }}</a-doption
              >
            </a-dgroup>
            <a-dgroup>
              <template #title>
                <div class="g-title"
                  ><img src="@/assets/images/xmmb.png" /><span
                    >项目模板</span
                  ></div
                >
              </template>
              <a-doption
                v-for="project in projectList.filter((e) => {
                  return e.isTemplate === 1;
                })"
                :key="project.id"
                :value="project.id"
                ><span class="prj-dot"></span>{{ project.name }}</a-doption
              >
            </a-dgroup>
          </template>
        </a-dropdown>
      </template>
    </div>
    <ul class="right-side">
      <li>
        <a-tooltip :content="$t('settings.language')">
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="setDropDownVisible"
          >
            <template #icon>
              <icon-language />
            </template>
          </a-button>
        </a-tooltip>
        <a-dropdown trigger="click" @select="changeLocale as any">
          <div ref="triggerBtn" class="trigger-btn"></div>
          <template #content>
            <a-doption
              v-for="item in locales"
              :key="item.value"
              :value="item.value"
            >
              <template #icon>
                <icon-check v-show="item.value === currentLocale" />
              </template>
              {{ item.label }}
            </a-doption>
          </template>
        </a-dropdown>
      </li>
      <li>
        <a-tooltip
          :content="
            theme === 'light'
              ? $t('settings.navbar.theme.toDark')
              : $t('settings.navbar.theme.toLight')
          "
        >
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="handleToggleTheme"
          >
            <template #icon>
              <icon-moon-fill v-if="theme === 'dark'" />
              <icon-sun-fill v-else />
            </template>
          </a-button>
        </a-tooltip>
      </li>
      <li>
        <a-tooltip :content="$t('settings.navbar.alerts')">
          <div class="message-box-trigger">
            <a-badge :count="9" dot>
              <a-button
                class="nav-btn"
                type="outline"
                :shape="'circle'"
                @click="setPopoverVisible"
              >
                <icon-notification />
              </a-button>
            </a-badge>
          </div>
        </a-tooltip>
        <a-popover
          trigger="click"
          :arrow-style="{ display: 'none' }"
          :content-style="{ padding: 0, minWidth: '400px' }"
          content-class="message-popover"
        >
          <div ref="refBtn" class="ref-btn"></div>
          <template #content>
            <message-box />
          </template>
        </a-popover>
      </li>
      <li>
        <a-tooltip
          :content="
            isFullscreen
              ? $t('settings.navbar.screen.toExit')
              : $t('settings.navbar.screen.toFull')
          "
        >
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="toggleFullScreen"
          >
            <template #icon>
              <icon-fullscreen-exit v-if="isFullscreen" />
              <icon-fullscreen v-else />
            </template>
          </a-button>
        </a-tooltip>
      </li>
      <li :style="{ padding: '0' }"
        ><a-divider
          direction="vertical"
          :margin="6"
          :style="{ fontSize: '32px' }"
      /></li>
      <li>
        <a-dropdown trigger="click">
          <div class="trigger-box">
            <div class="user-name">{{ userFullname }}</div>
            <a-avatar
              :size="32"
              :style="{ marginRight: '8px', cursor: 'pointer' }"
            >
              <img v-if="avatar" alt="avatar" :src="avatar" />
              <span v-else>{{ nickname }}</span>
            </a-avatar>
          </div>
          <template #content>
            <a-doption>
              <a-space @click="gotoUserCenter">
                <icon-settings />
                <span>
                  {{ $t('messageBox.userSettings') }}
                </span>
              </a-space>
            </a-doption>
            <a-doption>
              <a-space @click="handleLogout">
                <icon-export />
                <span>
                  {{ $t('messageBox.logout') }}
                </span>
              </a-space>
            </a-doption>
          </template>
        </a-dropdown>
      </li>
    </ul>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, onUnmounted, onMounted } from 'vue';
  import { useI18n } from 'vue-i18n';
  import { useDark, useToggle, useFullscreen } from '@vueuse/core';
  import { useAppStore, useUserStore, useGlobalModeStore } from '@/store';
  import { LOCALE_OPTIONS } from '@/locale';
  import useLocale from '@/hooks/locale';
  import useUser from '@/hooks/user';
  import {
    RouteLocationNormalized,
    RouteRecordName,
    useRoute,
    useRouter,
  } from 'vue-router';
  import {
    listenerRouteChange,
    removeRouteListener,
  } from '@/utils/route-listener';
  import useMenuTree from '@/components/menu/use-menu-tree';
  import logoTop from '@/assets/images/logo-top.png';
  import { getProjectList, ProjectListParams } from '@/api/project';
  import MessageBox from '../message-box/index.vue';

  interface ProjectRecord {
    id: string;
    name: string;
    isTemplate: 0 | 1;
  }

  const { t } = useI18n();

  const appStore = useAppStore();
  const userStore = useUserStore();
  const router = useRouter();
  const route = useRoute();
  const { logout } = useUser();
  const { changeLocale, currentLocale } = useLocale();
  const { isFullscreen, toggle: toggleFullScreen } = useFullscreen();
  const locales = [...LOCALE_OPTIONS];
  const avatar = computed(() => {
    return userStore.avatarToken;
  });
  const userFullname = computed(() => {
    return userStore.name || '未登录';
  });
  const nickname = computed(() => {
    return userFullname.value.substring(0, 1);
  });
  const theme = computed(() => {
    return appStore.theme;
  });
  const isDark = useDark({
    selector: 'body',
    attribute: 'arco-theme',
    valueDark: 'dark',
    valueLight: 'light',
    storageKey: 'arco-theme',
    onChanged(dark: boolean) {
      // overridden default behavior
      appStore.toggleTheme(dark);
    },
  });
  const toggleTheme = useToggle(isDark);
  const handleToggleTheme = () => {
    toggleTheme();
  };

  const refBtn = ref();
  const triggerBtn = ref();
  const setPopoverVisible = () => {
    const event = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true,
    });
    refBtn.value.dispatchEvent(event);
  };
  const handleLogout = () => {
    logout();
  };
  const setDropDownVisible = () => {
    const event = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true,
    });
    triggerBtn.value.dispatchEvent(event);
  };

  const modeList = computed(() => [
    {
      value: 'design',
      label: t('navbar.mode.design'),
      other: t('navbar.mode.design.mini'),
    },
    {
      value: 'file',
      label: t('navbar.mode.file'),
      other: t('navbar.mode.file.mini'),
    },
  ]);
  const globalModeStore = useGlobalModeStore();
  const globalMode = computed({
    get: () => globalModeStore.getGlobalMode,
    set: (mode) => {
      globalModeStore.changeGlobalMode(mode);
      const { menuTree } = useMenuTree();
      // 切换后当前菜单不在菜单树中，返回默认菜单项
      const isInMenuTree = menuTree.value.some(
        (item: any) => item.name === route.name
      );
      if (!isInMenuTree) {
        router.push({
          name: mode,
        });
      }
    },
  });
  const miniMode = computed<string>(() => {
    const idx = modeList.value.findIndex((v) => v.value === globalMode.value);
    return modeList.value[idx]?.other;
  });

  const projectModeControl = ref(false);
  const currentProjectId = ref(route.params.projectId || '');
  const projectList = ref<ProjectRecord[]>([]);
  const getList = () => {
    const params: ProjectListParams = {
      pageNo: 1,
      pageSize: 1000000,
      projectType: 2,
    };
    getProjectList(params).then((res: any) => {
      if (res.code === 8000000) {
        projectList.value = res.data?.list || [];
      }
    });
  };
  const currenPrjName = computed(() => {
    return projectList.value.find((v) => v.id === currentProjectId.value)?.name;
  });
  const projectChange = (
    id: string | number | Record<string, any> | undefined
  ) => {
    currentProjectId.value = id as string;
    router.push({
      name: route.name as RouteRecordName,
      params: {
        projectId: id as string,
      },
    });
  };

  // 监听路由变化，获取项目id并判断是否显示项目菜单
  const routeChangeHandle = (newRoute: RouteLocationNormalized) => {
    const projectId = newRoute.params.projectId || '';
    if (projectId) {
      projectModeControl.value = true;
      const flg = projectList.value.some((item) => item.id === projectId);
      if (!flg) {
        getList();
      }
      currentProjectId.value = projectId;
      // TODO: projectId不存在时显示异常页面,注意projectList和route参数异步的问题
    } else {
      projectModeControl.value = false;
    }
  };

  listenerRouteChange(routeChangeHandle, true);

  const toDashboard = () => {
    router.push({
      name: 'dashboard',
    });
  };
  const gotoUserCenter = () => {
    window.open(`${window.location.origin}/user-setting`);
  };

  onUnmounted(() => {
    // 顶部导航栏消失需要去除监听
    removeRouteListener();
  });
  onMounted(() => {
    getList();
  });
</script>

<style scoped lang="less">
  .navbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 100%;
    background-color: var(--color-bg-2);
    border-bottom: 1px solid var(--color-border);
  }

  .left-side {
    display: flex;
    align-items: center;
    padding-left: 8px;
    cursor: pointer;
  }

  .center-side {
    display: flex;
    align-items: center;
    flex: 1;
    //max-width: 860px;
    :deep(.project-select) {
      margin-left: 16px;
      padding: 0;
      background-color: transparent;
    }
    :deep(.arco-icon-down) {
      margin-left: 8px;
    }
  }
  .mode-box {
    display: flex;
    align-items: center;
    .mode-logo {
      width: 32px;
      height: 32px;
      background-color: rgba(var(--primary-6));
      border-radius: 4px;
      font-size: 17px;
      color: #ffffff;
      line-height: 32px;
      display: flex;
      justify-content: center;
    }
    :deep(.mode-select) {
      background-color: rgba(var(--primary-1));
      width: 145px;
    }
  }

  .g-title {
    display: flex;
    align-items: center;
    font-size: 14px;
    img {
      margin-right: 8px;
    }
  }
  .prj-dot {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: rgba(var(--primary-6));
    margin-right: 8px;
    margin-bottom: 1px;
  }

  .right-side {
    display: flex;
    padding-right: 20px;
    list-style: none;
    :deep(.locale-select) {
      border-radius: 20px;
    }
    li {
      display: flex;
      align-items: center;
      padding: 0 10px;
    }

    a {
      color: var(--color-text-1);
      text-decoration: none;
    }
    .nav-btn {
      border-color: rgb(var(--gray-2));
      color: rgb(var(--gray-8));
      font-size: 16px;
    }
    .trigger-btn,
    .ref-btn {
      position: absolute;
      bottom: 14px;
    }
    .trigger-btn {
      margin-left: 14px;
    }
  }
  .user-name {
    padding-right: 8px;
    cursor: pointer;
  }
  .trigger-box {
    display: flex;
    align-items: center;
  }
</style>

<style lang="less">
  .message-popover {
    .arco-popover-content {
      margin-top: 0;
    }
  }
  .arco-dropdown-open .arco-icon-down {
    transform: rotate(180deg);
  }
  .prj-dropdown {
    min-width: 200px;
  }
</style>
